Import libraries
import pandas as pd
import plotly.graph_objects as go
import datetime
from binance.client import Client
import numpy as np
import websocket
import json
import rel
import seaborn
import matplotlib as plt
Read CSV files and turn them into dataframes
csv1 = 'bitcoin.csv'
csv2 = 'ethereum.csv'
Initialise client for Binance API
api_key = 'api_key'
api_secret = 'no no no'
client = Client(api_key, api_secret)
symbol1 = 'BTCUSDT'
interval1 = '1m'
start1 = ''
end1 = ''
symbol2 = 'ETHUSDT'
interval2 = '1m'
start2 = ''
end2 = ''
symbol3 = 'LTCUSDT'
interval3 = '1m'
start3 = ''
end3 = ''
Get data from the API and function to turn into dataframe
klines1 = np.array(client.get_historical_klines(symbol1, interval1))
klines2 = np.array(client.get_historical_klines(symbol2, interval2))
klines3 = np.array(client.get_historical_klines(symbol3, interval3))
def binanceDataFrame(klines):
df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns = ('time', 'open', 'high', 'low', 'close', 'volume', 'close_time', ' quote_volume', 'count', 'taker_buy_volume', 'taker_buy_quote_volume', 'ignore'))
df['time'] = pd.to_datetime(df['time'], unit='ms')
return df
pair1 = binanceDataFrame(klines1)
pair2 = binanceDataFrame(klines2)
pair3 = binanceDataFrame(klines3)
Plot data using plotly
def candlestickplot(df):
fig = go.Figure(data=[go.Candlestick(x=df['time'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'])])
return fig
fig1 = candlestickplot(pair1)
fig2 = candlestickplot(pair2)
fig3 = candlestickplot(pair3)
fig1.update_layout(title=symbol1, xaxis_rangeslider_visible = False)
fig2.update_layout(title=symbol2, xaxis_rangeslider_visible = False)
fig3.update_layout(title=symbol3, xaxis_rangeslider_visible = False)
fig1.show()
fig2.show()
fig3.show()
socket = f'wss://stream.binance.com:9443/stream?streams={symbol1.lower()}@kline_{interval1}/{symbol2.lower()}@kline_{interval2}/{symbol3.lower()}@kline_{interval3}'
def on_open(ws):
print('---------Opened----------')
def on_message(ws, message):
jsonmessage = json.loads(message)
data = jsonmessage['data']
symbol = data['s']
candle = data['k']
time = datetime.datetime.fromtimestamp(candle['t']/1000.0)
open = candle['o']
close = candle['c']
high = candle['h']
low = candle['l']
closed = candle['x']
if closed:
print(f'{symbol}: opened at {open}, closed at {close} at {time}')
websocket.enableTrace(False)
ws = websocket.WebSocketApp(socket, on_message = on_message, on_open = on_open)
ws.run_forever()
Running statistical analysis
closes = pd.concat([pair1['close'], pair2['close'], pair3['close']], axis = 1)
closes.columns = [symbol1, symbol2,symbol3]
correlation = closes.corr()
heatmap = seaborn.heatmap(correlation, cmap="crest", annot = True)